package org.xin.security.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.xin.common.util.XinUtil;
import org.xin.framework.config.exception.CloudException;
import org.xin.security.pojo.bo.SecurityUser;
import org.xin.security.common.UserStatus;
import org.xin.security.component.PermissionMangerComponent;
import org.xin.security.pojo.bo.UserInfo;
import org.xin.security.pojo.entity.SysUser;
import org.xin.security.pojo.entity.SysUserSecurity;
import org.xin.security.service.ISysUserSecurityService;
import org.xin.security.service.ISysUserService;

/**
 * @author ：xin
 * @date ：Created in 2021/10/2
 * @desc <p>  </p>
 * @modified By：$
 * @version: $
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private ISysUserSecurityService userSecurityService;
    @Autowired
    private ISysUserService userService;

    @Autowired
    private PermissionMangerComponent permissionMangerComponent;

    @Override
    public UserDetails loadUserByUsername(String username) {
        SysUserSecurity userSecurity = userSecurityService.selectByUsername(username);
        if (XinUtil.isNull(userSecurity)) {
            log.info("登录用户：{} 不存在.", username);
            throw new CloudException("登录用户：" + username + " 不存在");
        } else if (UserStatus.DELETED.getCode().equals(userSecurity.getIsDelete())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new CloudException("对不起，您的账号：" + username + " 已被删除");
        } else if (UserStatus.DISABLE.getCode().equals(userSecurity.getUserStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new CloudException("对不起，您的账号：" + username + " 已停用");
        }
        SysUser sysUser = userService.getById(userSecurity.getSysUserId());
        if (XinUtil.isNull(sysUser)) {
            log.info("登录用户：{} 信息异常.", username);
            throw new CloudException("对不起，您的账号：" + username + " 信息异常");
        }
        return createLoginUser(userSecurity, sysUser);
    }

    public UserDetails createLoginUser(SysUserSecurity userSecurity, SysUser user) {
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userSecurity, userInfo);
        BeanUtils.copyProperties(user, userInfo);
        return SecurityUser.builder()
                .userId(user.getId())
                .deptId(userSecurity.getSysDeptId())
                .user(userInfo)
                .permissions(permissionMangerComponent.getMenuPermission(userInfo))
                .build();
    }
}
